package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.omg.PortableInterceptor.INACTIVE;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class BindGiteeController {

    @Autowired
    UserMapper userMapper;


    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletRequest request, HttpServletResponse response){

        System.out.println("接收到的临时授权码" + code);

        String token = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token" + token);
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(token);
        System.out.println("获取到的用户信息" + JSONObject.toJSONString(userInfoByToken));

        Integer giteeId = userInfoByToken.getInteger("id");
        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString(GiteeUtils.UserInfoPropertyEnum.AVATAR_URL.getKey());

        // 进行账号的合并
        // 获取当前登录的用户
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);
        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);
        userFromRequest.setGiteeId(giteeId);

        userMapper.updateUser(userFromRequest);

        // 重新制作学生证,重新加密用户信息
        TokenUtils.responseTokenByCookie(userFromRequest,response);

        return "redirect:list.do";
    }
}
